document.addEventListener('DOMContentLoaded', () => {
    // 获取Canvas元素
    const canvas = document.getElementById('fireworks');
    const ctx = canvas.getContext('2d');

    // 设置Canvas大小为窗口大小
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    // 烟花粒子数组
    let particles = [];
    // 烟花火箭数组
    let rockets = [];
    // 上次添加火箭的时间
    let lastRocket = Date.now();
    // 重力
    const gravity = 0.2;
    // 烟花发射频率（毫秒）
    let rocketFrequency = 700;

    // 颜色数组
    const colors = [
        '#FF5252', '#FF4081', '#E040FB', '#7C4DFF', '#536DFE',
        '#448AFF', '#40C4FF', '#18FFFF', '#64FFDA', '#69F0AE',
        '#B2FF59', '#EEFF41', '#FFFF00', '#FFD740', '#FFAB40',
        '#FF6E40'
    ];

    // 创建星星背景
    const stars = [];
    for (let i = 0; i < 100; i++) {
        stars.push({
            x: Math.random() * canvas.width,
            y: Math.random() * canvas.height,
            radius: Math.random() * 1.5,
            alpha: Math.random(),
            direction: Math.random() > 0.5 ? 0.005 : -0.005
        });
    }

    // 文字烟花配置
    let textConfig = {
        text: '',
        size: 40,
        color: '#ffffff',
        effect: 'fade'
    };

    // 粒子类
    class Particle {
        constructor(x, y, color) {
            this.x = x;
            this.y = y;
            this.color = color;
            this.alpha = 1;
            this.size = Math.random() * 3 + 1;
            
            // 随机速度和方向
            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 6 + 2;
            this.vx = Math.cos(angle) * speed;
            this.vy = Math.sin(angle) * speed;
            
            // 粒子生命周期
            this.lifetime = Math.random() * 30 + 50;
            this.age = 0;
            
            // 粒子闪烁效果
            this.flicker = Math.random() < 0.5;
            this.flickerRate = Math.random() * 0.2 + 0.1;
        }

        update() {
            // 更新位置
            this.x += this.vx;
            this.y += this.vy;
            
            // 应用重力
            this.vy += gravity;
            
            // 减小速度（空气阻力）
            this.vx *= 0.98;
            this.vy *= 0.98;
            
            // 粒子逐渐变小和透明
            this.size *= 0.96;
            this.alpha = (this.lifetime - this.age) / this.lifetime;
            
            // 闪烁效果
            if (this.flicker) {
                this.alpha *= Math.sin(this.age * this.flickerRate) * 0.5 + 0.5;
            }
            
            // 增加年龄
            this.age++;
            
            // 返回粒子是否存活
            return this.age < this.lifetime && this.alpha > 0.01 && this.size > 0.1;
        }

        draw() {
            ctx.globalAlpha = this.alpha;
            ctx.fillStyle = this.color;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
            ctx.globalAlpha = 1;
        }
    }

    // 文字烟花类
    class TextFirework {
        constructor(x, y, text, options) {
            this.x = x;
            this.y = y;
            this.text = text;
            this.size = options.size;
            this.color = options.color;
            this.effect = options.effect;
            this.alpha = 0;
            this.lifetime = 100;
            this.age = 0;
            this.scale = 1;
            this.rotation = 0;
        }

        update() {
            this.age++;
            
            switch(this.effect) {
                case 'fade':
                    this.alpha = this.age < 20 ? this.age / 20 : (this.lifetime - this.age) / (this.lifetime - 20);
                    break;
                case 'scatter':
                    this.alpha = (this.lifetime - this.age) / this.lifetime;
                    this.scale = 1 + (this.age / this.lifetime);
                    break;
                case 'rotate':
                    this.alpha = this.age < 20 ? this.age / 20 : (this.lifetime - this.age) / (this.lifetime - 20);
                    this.rotation = (this.age / this.lifetime) * Math.PI * 2;
                    break;
            }

            return this.age < this.lifetime;
        }

        draw() {
            if (this.alpha <= 0) return;

            ctx.save();
            ctx.globalAlpha = this.alpha;
            ctx.fillStyle = this.color;
            ctx.font = `${this.size}px Arial`;
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';

            ctx.translate(this.x, this.y);
            ctx.scale(this.scale, this.scale);
            ctx.rotate(this.rotation);
            
            ctx.fillText(this.text, 0, 0);
            ctx.restore();
        }
    }

    // 火箭类
    class Rocket {
        constructor() {
            // 从底部随机位置发射
            this.x = Math.random() * canvas.width;
            this.y = canvas.height;
            
            // 目标高度
            const targetHeight = Math.random() * (canvas.height * 0.5) + canvas.height * 0.2;
            
            // 计算速度
            const angle = Math.PI / 2; // 向上发射
            const speed = 8 + Math.random() * 6;
            this.vx = Math.cos(angle) * speed * (Math.random() - 0.5);
            this.vy = -Math.sin(angle) * speed;
            
            // 火箭尾迹粒子
            this.trailParticles = [];
            
            // 火箭颜色
            this.color = colors[Math.floor(Math.random() * colors.length)];
            
            // 火箭大小
            this.size = 2;
            
            // 目标高度
            this.targetY = targetHeight;
            
            // 是否已爆炸
            this.exploded = false;
        }

        update() {
            if (this.exploded) return false;
            
            // 更新位置
            this.x += this.vx;
            this.y += this.vy;
            
            // 应用重力
            this.vy += gravity * 0.1;
            
            // 创建尾迹粒子
            if (Math.random() < 0.5) {
                this.trailParticles.push(new Particle(
                    this.x, 
                    this.y, 
                    this.color
                ));
            }
            
            // 更新尾迹粒子
            for (let i = this.trailParticles.length - 1; i >= 0; i--) {
                if (!this.trailParticles[i].update()) {
                    this.trailParticles.splice(i, 1);
                }
            }
            
            // 检查是否到达最高点或速度变为向下
            if (this.y <= this.targetY || this.vy >= 0) {
                this.explode();
                return false;
            }
            
            return true;
        }

        draw() {
            // 绘制火箭
            ctx.fillStyle = this.color;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制尾迹粒子
            for (const particle of this.trailParticles) {
                particle.draw();
            }
        }

        explode() {
            this.exploded = true;
            
            // 创建爆炸粒子
            const particleCount = 80 + Math.floor(Math.random() * 50);
            for (let i = 0; i < particleCount; i++) {
                particles.push(new Particle(this.x, this.y, this.color));
            }
            
            // 随机添加一些不同颜色的粒子
            const secondaryColor = colors[Math.floor(Math.random() * colors.length)];
            for (let i = 0; i < particleCount / 3; i++) {
                particles.push(new Particle(this.x, this.y, secondaryColor));
            }

            // 如果有文字，创建文字烟花
            if (textConfig.text) {
                textFireworks.push(new TextFirework(
                    this.x,
                    this.y,
                    textConfig.text,
                    {
                        size: textConfig.size,
                        color: textConfig.color,
                        effect: textConfig.effect
                    }
                ));
            }
        }
    }

    // 文字烟花数组
    let textFireworks = [];

    // 绘制星星背景
    function drawStars() {
        ctx.fillStyle = '#FFFFFF';
        for (const star of stars) {
            ctx.globalAlpha = star.alpha;
            ctx.beginPath();
            ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
            ctx.fill();
            
            // 星星闪烁效果
            star.alpha += star.direction;
            if (star.alpha <= 0.1 || star.alpha >= 0.9) {
                star.direction *= -1;
            }
        }
        ctx.globalAlpha = 1;
    }

    // 添加新火箭
    function addRocket() {
        const now = Date.now();
        // 使用设置的频率控制发射间隔
        // 频率越高（值越小），发射间隔越短；频率越低（值越大），发射间隔越长
        if (now - lastRocket > (Math.random() * 300 + rocketFrequency)) {
            rockets.push(new Rocket());
            lastRocket = now;
        }
    }

    // 点击添加火箭
    canvas.addEventListener('click', (e) => {
        const rocket = new Rocket();
        // 设置火箭位置为点击位置的下方
        rocket.x = e.clientX;
        rocket.y = canvas.height;
        // 设置目标为点击位置
        rocket.targetY = e.clientY;
        // 调整速度以到达目标
        const angle = Math.atan2(canvas.height - e.clientY, e.clientX - rocket.x);
        const speed = 8 + Math.random() * 6;
        rocket.vx = Math.cos(angle) * speed;
        rocket.vy = -Math.sin(angle) * speed;
        
        rockets.push(rocket);
    });

    // 窗口大小改变时调整Canvas大小
    window.addEventListener('resize', () => {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    });

    // 频率控制滑块
    const frequencySlider = document.getElementById('frequency-slider');
    const frequencyValue = document.getElementById('frequency-value');

    // 更新频率显示文本
    function updateFrequencyText(value) {
        if (value <= 300) {
            return '极高';
        } else if (value <= 600) {
            return '高';
        } else if (value <= 900) {
            return '中等';
        } else if (value <= 1500) {
            return '低';
        } else {
            return '极低';
        }
    }

    // 初始化频率显示
    frequencyValue.textContent = updateFrequencyText(frequencySlider.value);

    // 监听滑块变化
    frequencySlider.addEventListener('input', (e) => {
        rocketFrequency = parseInt(e.target.value);
        frequencyValue.textContent = updateFrequencyText(rocketFrequency);
    });

    // 动画循环
    function animate() {
        // 清除画布
        ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 绘制星星
        drawStars();
        
        // 添加新火箭
        addRocket();
        
        // 更新和绘制火箭
        for (let i = rockets.length - 1; i >= 0; i--) {
            if (!rockets[i].update()) {
                rockets.splice(i, 1);
            } else {
                rockets[i].draw();
            }
        }
        
        // 更新和绘制粒子
        for (let i = particles.length - 1; i >= 0; i--) {
            if (!particles[i].update()) {
                particles.splice(i, 1);
            } else {
                particles[i].draw();
            }
        }
        
        // 更新文字烟花
        for (let i = textFireworks.length - 1; i >= 0; i--) {
            if (!textFireworks[i].update()) {
                textFireworks.splice(i, 1);
            }
        }
        
        // 绘制文字烟花
        for (const textFirework of textFireworks) {
            textFirework.draw();
        }
        
        // 继续动画循环
        requestAnimationFrame(animate);
    }

    // 启动动画
    animate();

    // 添加事件监听器
    const textInput = document.getElementById('firework-text');
    const addTextBtn = document.getElementById('add-text');
    const textSize = document.getElementById('text-size');
    const textColor = document.getElementById('text-color');
    const textEffect = document.getElementById('text-effect');
    const templateBtns = document.querySelectorAll('.text-templates button');

    // 更新文字配置
    function updateTextConfig() {
        textConfig.text = textInput.value;
        textConfig.size = parseInt(textSize.value);
        textConfig.color = textColor.value;
        textConfig.effect = textEffect.value;
    }

    // 添加文字按钮点击事件
    addTextBtn.addEventListener('click', () => {
        updateTextConfig();
        if (!textConfig.text) return;
        addRocket();
    });

    // 文字输入回车事件
    textInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            updateTextConfig();
            if (!textConfig.text) return;
            addRocket();
        }
    });

    // 模板按钮点击事件
    templateBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            textInput.value = btn.dataset.text;
            updateTextConfig();
            addRocket();
        });
    });

    // 监听选项变化
    textSize.addEventListener('input', updateTextConfig);
    textColor.addEventListener('input', updateTextConfig);
    textEffect.addEventListener('change', updateTextConfig);
});

